﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Ongoal.Quotation
{
    /// <summary>
    /// 
    /// </summary>
    public class AuthenticationProvider: IAuthentication
    {
        private IConfiguration _configuration;
        private string _base64Secret;
        private JwtConfig _jwtConfig = new JwtConfig();
        public AuthenticationProvider(IConfiguration configration, JwtConfig jwt)
        {
            this._configuration = configration;
            _jwtConfig = jwt;
            GetSecret();
        }

        /// <summary>
        /// 获取到加密串
        /// </summary>
        private void GetSecret()
        {
            this._base64Secret = this._jwtConfig.SecretKey;
        }
        /// <summary>
        /// 生成Token
        /// </summary>
        /// <param name="Clims"></param>
        /// <returns></returns>
        public string GetToken(List<Claim> Clims)
        {
            var symmetricKey = System.Text.Encoding.UTF8.GetBytes(this._base64Secret);//Convert.FromBase64String(this._base64Secret);
            var tokenHandler = new JwtSecurityTokenHandler();
            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Issuer = _jwtConfig.Issuer,
                Audience = _jwtConfig.Audience,
                Subject = new ClaimsIdentity(Clims),
                NotBefore = DateTime.Now.AddSeconds(-30),
                Expires = DateTime.Now.AddHours(this._jwtConfig.Lifetime),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey),
               SecurityAlgorithms.HmacSha256Signature)
            };
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(securityToken);
        }
        /// <summary>
        /// 验证Token
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="Clims"></param>
        /// <returns></returns>
        public bool ValidateToken(string Token, out List<Claim> Clims)
        {
            Clims = new List<Claim>();
            if (string.IsNullOrWhiteSpace(Token))
            {
                return false;
            }
            var handler = new JwtSecurityTokenHandler();
            try
            {
                var jwt = handler.ReadJwtToken(Token);

                if (jwt == null)
                {
                    return false;
                }
                var secretBytes = System.Text.Encoding.UTF8.GetBytes(this._base64Secret);// Convert.FromBase64String(this._base64Secret);
                var validationParameters = new TokenValidationParameters
                {
                    RequireExpirationTime = true,
                    IssuerSigningKey = new SymmetricSecurityKey(secretBytes),
                    ClockSkew = TimeSpan.Zero,
                    ValidateIssuer = true,//是否验证Issuer
                    ValidateAudience = true,//是否验证Audience
                    ValidateLifetime = this._jwtConfig.ValidateLifetime,//是否验证失效时间
                    ValidateIssuerSigningKey = true,//是否验证SecurityKey
                    ValidAudience = this._jwtConfig.Audience,
                    ValidIssuer = this._jwtConfig.Issuer
                };
                SecurityToken securityToken;
                ClaimsPrincipal principal = handler.ValidateToken(Token, validationParameters, out securityToken);
                if (principal != null)
                    Clims = principal.Claims.ToList();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return false;
            }
        }

        /// <summary>
        /// 获取刷新Token
        /// </summary>
        /// <param name="Clims"></param>
        /// <returns></returns>
        public string GetRefreshToken(List<Claim> Clims)
        {
            var symmetricKey = System.Text.Encoding.UTF8.GetBytes(this._base64Secret); //Convert.FromBase64String(this._base64Secret);
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Issuer = _jwtConfig.Issuer,
                Audience = _jwtConfig.Audience,
                Subject = new ClaimsIdentity(Clims),
                NotBefore = DateTime.Now,
                Expires = DateTime.Now.AddDays(2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey),
                            SecurityAlgorithms.HmacSha256Signature)
            };
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(securityToken);
        }
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        public List<Claim> GetClaims(string Token)
        {
            if (string.IsNullOrEmpty(Token))
                return null;
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(Token);
            return jwtToken.Claims.ToList();
        }
    }
}
